<!-- 导入文件弹框，处理导入结果 -->
<template>
  <a-modal
    v-if="props.isModal"
    v-model:visible="vdata.visible"
    width="40%"
    :mask-closable="false"
    :title="props.title"
    :footer="null"
    @cancel="handleCancel"
  >
    <a-row>
      <a-col :span="12">总条数：{{ vdata.total }}</a-col>
      <a-col :span="12">已处理条数：{{ vdata.success + vdata.fail }}</a-col>
      <a-col :span="12">正确条数：{{ vdata.success }}</a-col>
      <a-col :span="12">错误条数：{{ vdata.fail }}</a-col>
    </a-row>
    <!-- 结果滚动区域 -->
    <a-row>
      <textarea
        ref="resultLogRef"
        :value="vdata.importResult"
        class="result-log"
        disabled
      />
    </a-row>
    <!-- 进度条 -->
    <a-row>
      <div class="process-box">
        <div class="process-bar" :style="processStyle" />
      </div>
    </a-row>
  </a-modal>
  <template v-else>
    <a-row v-if="props.isOuterResult">
      <a-col :span="12">总条数：{{ props.outerResult.total }}</a-col>
      <a-col :span="12">已处理条数：{{ props.outerResult.success + props.outerResult.fail }}</a-col>
      <a-col :span="12">正确条数：{{ props.outerResult.success }}</a-col>
      <a-col :span="12">错误条数：{{ props.outerResult.fail }}</a-col>
    </a-row>
    <a-row v-else>
      <a-col :span="12">总条数：{{ vdata.total }}</a-col>
      <a-col :span="12">已处理条数：{{ vdata.success + vdata.fail }}</a-col>
      <a-col :span="12">正确条数：{{ vdata.success }}</a-col>
      <a-col :span="12">错误条数：{{ vdata.fail }}</a-col>
    </a-row>
    <!-- 结果滚动区域 -->
    <a-row>
      <textarea
        ref="resultLogRef"
        :value="props.isOuterResult ? props.outerResult.errorMessage : vdata.importResult"
        class="result-log"
        disabled
      />
    </a-row>
    <!-- 进度条 -->
    <a-row v-if="!props.isOuterResult">
      <div class="process-box">
        <div class="process-bar" :style="processStyle" />
      </div>
    </a-row>
  </template>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, defineExpose, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useUserStore } from '@/store/modules/user'
import createWebSocket from '@/websocket/websocket-factory.js'

// refs
const resultLogRef = ref(null)

// 定义props
const props = defineProps({
  title: {
    type: String,
    default: '导入结果'
  },
  isModal: {
    type: Boolean,
    default: true
  },
  // 外部结果优先级高于内部结果
  isOuterResult: {
    type: Boolean,
    default: false
  },
  outerResult: {
    type: Object,
    default: () => {
      return {
        total: 0,
        success: 0,
        fail: 0,
        errorMessage: ''
      }
    }
  }
})

// 全局websocket变量
let ws = null
// 数据源
const vdata = reactive({
  visible: false, // 弹框是否可见
  importResult: '', // 导入结果

  total: 0, // 总条数
  current: 0, // 当前处理条数
  success: 0, // 成功条数
  fail: 0, // 错误条数
})

// 计算属性
const processStyle = computed(() => {
  return {
    'width': `${vdata.current / vdata.total * 100}%`,
    'background-color': vdata.current > 0 ? '#4287ff' : '#f0f0f0',
  }
})

// 卸载
onUnmounted(() => {
  // 关闭ws链接
  if (ws) {
    ws.close()
  }
})

// cancelHandler
function handleCancel() {
  vdata.visible = false
  // 关闭websocket
  if (ws) {
    ws.close()
  }
}

// 导入结果重置
function resetImportResult() {
  vdata.importResult = ''
  vdata.total = 0
  vdata.current = 0
  vdata.success = 0
  vdata.fail = 0
}

// 初始化websocket
function initWebsocket() {
  ws = createWebSocket(`/${useUserStore().userInfo.sysUserId}`)
  ws.onMessage(handleWebsocketMsg)
  ws.connect()
}

// websocket消息处理  msg: { "total": 100, "status": "FAIL", "topic": "251370", "payloadType": "SINGLE_ENTITY", "eventDesc": "导入平台商户数据", "content": "第90行，代理商号不能为空", "timestamp": 1753166711122}
// 批处理队列
const batchQueue = ref('')
const flushTimer = ref(null)
const batchInterval = ref(10) // 批处理间隔(ms)
function handleWebsocketMsg(msg) {
  vdata.current += 1
  if(msg.total !== vdata.total){
    vdata.total = msg.total
  }
  if(msg.status === 'FAIL'){
    vdata.fail += 1
  }else if(msg.status === 'SUCCESS'){
    vdata.success += 1
  }

  batchQueue.value += msg.content + '\n'

  // 启动批处理防抖
  if (!flushTimer.value) {
    flushTimer.value = setTimeout(flushBatch, batchInterval.value)
  }
  // 拼接结果

  // vdata.importResult += msg.content + '\n'
  // if(vdata.total === vdata.current){
  //   vdata.importResult += '导入完成！'
  // }
}

// 处理批处理队列
const flushBatch = () => {
  if (batchQueue.value !== '') {
    // 添加新数据（使用扩展运算符创建新数组以触发响应式更新）
    vdata.importResult += batchQueue.value
    // 清空批处理队列
    batchQueue.value = ''
  }
  
  // 重置计时器
  clearTimeout(flushTimer.value)
  flushTimer.value = null
  
  // 自动滚动到底部
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    resultLogRef.value.scrollTop = resultLogRef.value.scrollHeight
  })
}


// 弹窗显示
function pageRender() {
  // 初始化websocket
  initWebsocket()
  // 重置数据
  vdata.src = ''
  vdata.importResult = ''
  vdata.total = 0
  vdata.current = 0
  vdata.success = 0
  vdata.fail = 0

  vdata.visible = true
}

// 暴露事件
defineExpose({
  pageRender,
  wsClose: () => {
    if (ws) {
      ws.close()
    }
  },
  resetImportResult
})
</script>

<style lang="less" scoped>
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.result-log {
  width: 100%;
  padding: 15px;
  margin-top: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  animation: fadeIn 0.3s ease-out;
  background-color: #e6e6e6;
  color: #000000;
  height: 150px;
}

.process-box {
  width: 100%;
  height: 10px;
  background-color: #e6e6e6;

  .process-bar {
    width: 0;
    max-width: 100%;
    height: 10px;
    transition: width 0.3s ease-out;
  }
}
</style>